/**
 * 权限中间件
 */
const { httpStatusCode } = require('@root/types/HttpStatusCode.js')
const { poolPromise } = require("@root/db/index")
const { SuperAdminId } = require("@root/config/index")



/**
 * 校验用户是否有该接口权限
 * @param {string[]} permissions
 * @returns
 */
function checkInterfaceAccessPermission(permissions) {
  return async (req, res, next) => {
    try {
      const { roles } = req.auth

      if (!roles?.length) {
        return res.status(httpStatusCode.Conflict).json({ code: httpStatusCode.Conflict, message: '该用户未分配角色' });
      }
      const roleIds = roles.map(item => item.role_id)

      // 超级管理员拥有所有权限， 直接放行
      if (roleIds.includes(SuperAdminId)) next()

      const permission_sql = `select distinct s_m.perms from sys_menu s_m left join sys_role_menu s_r_m on s_m.menu_id = s_r_m.menu_id where s_r_m.role_id in (${roleIds.join(',')})`
      // 根据当前用户的角色id 查出对应的角色的权限集合
      const [permits] = await poolPromise.execute(permission_sql)
      const curRolePermissions = permits.map(item => item.perms)
      // 判断当前用户是否有该接口权限
      const isCheck = permissions.some(permission => curRolePermissions.includes(permission))
      if (isCheck) next()
      else res.status(httpStatusCode.Forbidden).json({ code: httpStatusCode.Forbidden, message: '没有权限进行此操作' })
    } catch (error) {
      next(error)
    }
  };
}

module.exports = {
  checkInterfaceAccessPermission
}